import { message, Select } from "antd";
import { GetFieldDecoratorOptions } from "antd/lib/form/Form";
import { addon, log, Permission } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import FormCreator, { InputType } from "src/business/components/buss-components/form-creator";
import { InputType as ListInputType } from "src/business/components/buss-components/sign-frame-layout";
import { MainContent } from "src/business/components/style-components/main-content";
import { decodeUrlParam } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { edit_props_info } from "src/projects/app/util-tool";
import { ROUTE_PATH } from "src/projects/router";
import './index.less';
let { Option } = Select;
let services: any[] = [];
message.config({
    top: 350,
});

/**
 * 组件：帮长者购买服务状态
 */
export interface BuyServiceViewState extends ReactViewState {

    /** 滚动条 */
    loading?: boolean;
    /** 基础数据 */
    base_data: any;
    /** 服务商列表 */
    service_p_list?: any[];
    /** 服务列表 */
    service?: any[];
    /** 价格 */
    total_price?: number;
    /** 长者信息 */
    older_info?: any;
    /** 服务列表 */
    service_list?: any[];
    // 账户余额
    balance?: number;
    // 服务商id
    servicer_id?: string;
}

/**
 * 组件：帮长者购买服务视图
 */
export class BuyServiceView extends ReactView<BuyServiceViewControl, BuyServiceViewState> {
    private columns_data_source = [{
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
    }, {
        title: '身份证号',
        dataIndex: 'id_card',
        key: 'id_card',
    }, {
        title: '性别',
        dataIndex: 'personnel_info.sex',
        key: 'personnel_info.sex',
    },
        // {
        //     title: '出生年月',
        //     dataIndex: 'personnel_info.birth_date',
        //     key: 'personnel_info.birth_date',
        // }
    ];
    constructor(props: any) {
        super(props);
        this.state = {
            loading: false,
            base_data: {},
            service_p_list: [],
            service: [],
            total_price: 0,
            older_info: undefined,
            service_list: [],
            balance: 0,
            servicer_id: '',
        };
    }
    /** 确定回调 */
    handleSubmit = (err: Error, values: any) => {
        // let id = this.props.match!.params.key;
        if (values) {
            let id = values.service_product_id.split('/')[0];
            AppServiceUtility.comfirm_order_service.batch_create_order!(
                {
                    'service_product_id': id,
                    'name': values.name,
                    'amout': values.amout,
                    'service_provider_id': values.service_provider_id,
                    'comment': values.comment,
                    'address': values.address,
                    'order_state': '待分派',
                    'organization_id': values.service_provider_id,
                    'buy_type': values.buy_type,
                },
                values.amout)!
                .then((data: any) => {
                    if (data === 'Success') {
                        message.info('下单成功');
                        this.props.history!.push(ROUTE_PATH.buyService);
                    } else {
                        message.error(data);
                    }
                })
                .catch(error => {
                    message.error(error.message);
                });
        }
    }
    componentDidMount() {
        AppServiceUtility.person_org_manage_service.get_organization_list!({ "personnel_category": "服务商" })!
            .then(data => {
                this.setState({
                    service_p_list: data!.result
                });
            })
            .catch(err => {
                console.info(err);
            });
    }
    service_providerChange = (value: any) => {
        this.setState({
            servicer_id: value
        });

    }
    add_service = (i: number, item: any) => {
        if (i === 2) {
            services = services!.concat(item);
            this.setState({
                service: services
            });
            services = [];
        } else {
            services = services!.concat(item);
        }

    }
    service_change = (value: any) => {
        let s = value.split('/');
        if (s[1] === 'false') {
            AppServiceUtility.service_item_service.get_service_product_package_list!({ "id": s[0] })!
                .then(data => {
                    this.setState({
                        total_price: data!.result![0]['total_price'],
                    });

                })
                .catch(err => {
                    console.info(err);
                });

        } else {
            AppServiceUtility.service_item_serviceinfo.get_service_product_list({ "id": s[0] })!
                .then(data => {
                    this.setState({
                        total_price: data!.result![0]['total_price'],
                    });
                })
                .catch(err => {
                    console.info(err);
                });
        }

    }
    older_change = (value: any) => {
        AppServiceUtility.person_org_manage_service.get_elder_list!({ id: value }, 1, 1)!
            .then(data => {
                this.setState({
                    base_data: data.result![0],
                });
            })
            .catch(err => {
                console.info(err);
            });

    }
    account_type_change = (value: any) => {
        if (value === '补贴账户') {
            AppServiceUtility.subsidy_account_recharg_service.get_account_balance!({ user_id: this.state.base_data.id, account_name: '补贴账户' }, 1, 1)!
                .then(data => {
                    console.info(data);
                    if (data!.result) {
                        this.setState({
                            balance: data!.result[0].balance,
                        });
                    }
                })
                .catch(err => {
                    console.info(err);
                });
        }
    }
    product_type_change = (value: any) => {
        let { servicer_id } = this.state;
        if (value === '单项') {
            AppServiceUtility.service_item_serviceinfo.get_service_product_list({ "organization_id": servicer_id })!
                .then(data => {
                    this.setState({
                        service: data.result
                    });
                })
                .catch(err => {
                    console.info(err);
                });
        } else {
            AppServiceUtility.service_item_service.get_service_product_package_list!({ "organization_id": servicer_id })!
                .then(data => {
                    this.setState({
                        service: data.result
                    });
                })
                .catch(err => {
                    console.info(err);
                });
        }
    }
    componentWillMount() {
        if (this.props.match!.params.key !== undefined) {
            // TODO:
            const older_id = decodeUrlParam(this.props.match!.params.key);
            AppServiceUtility.person_org_manage_service.get_elder_list!({ id: older_id }, 1, 1)!
                .then((data) => {
                    log('长者数据', data.result![0]);
                    if (data) {
                        this.setState({
                            base_data: data.result![0],
                        });
                    }
                });
        }
    }

    render() {
        let buy_type_list = ['补贴账户', '慈善账户'];
        let product_type_list = ['单项', '产品'];
        let { service_p_list, service } = this.state;
        let org_type_list: any[] = [];
        let service_list: any[] = [];
        let buy_type_dom: any[] = [];
        let product_type_dom: any[] = [];
        service_p_list!.map((item) => {
            org_type_list.push(<Option key={item.id}>{item.name}</Option>);
        });

        service!.map((item) => {
            let pNmae = '';
            pNmae = item.is_service_item === 'true' ? item.name + '__单项' : item.name + '__产品';
            service_list.push(<Option key={item.id + '/' + item.is_service_item}>{pNmae}</Option>);
        });
        console.info(service_list);
        buy_type_list.map((item) => {
            buy_type_dom.push(<Option key={item}>{item}</Option>);
        });
        product_type_list.map((item) => {
            product_type_dom.push(<Option key={item}>{item}</Option>);
        });
        let { base_data } = this.state;
        let modal_search_items_props = {
            type: 'input',
            edit_form_items_props: [
                {
                    type: ListInputType.input,
                    label: "长者名称",
                    decorator_id: "name"
                },
                {
                    type: ListInputType.input,
                    label: "身份证号码",
                    decorator_id: "id_card"
                },
            ],
            columns_data_source: this.columns_data_source,
            service_name: AppServiceUtility.person_org_manage_service,
            service_func: 'get_elder_list',
            service_option: base_data.id ? [{ id: base_data.id }, 1, 1] : '',
            title: '长者查询',
            select_option: {
                placeholder: "请选择长者",
            }
        };
        let service_option = {
            service_object: AppServiceUtility.person_org_manage_service,
            operation_option: {
                save: {
                    func_name: "update_organization"
                },
                query: {
                    func_name: "",
                    arguments: [{ id: this.props.match!.params.key }, 1, 1]
                }
            },
        };

        let edit_props = {
            form_items_props: [
                {
                    title: "购买服务",
                    need_card: true,
                    input_props: [
                        {
                            type: InputType.modal_search,
                            label: "长者姓名",
                            decorator_id: 'name',
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入名称" }],
                                initialValue: base_data.id ? base_data.id : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请选择长者姓名",
                                modal_search_items_props: modal_search_items_props,
                                onChange: this.older_change
                            },
                        },
                        {
                            type: InputType.antd_input,
                            label: "证件号码",
                            decorator_id: "id_card",
                            field_decorator_option: {
                                rules: [{ required: false, message: "请输入证件号码" }],
                                initialValue: base_data.id_card ? base_data.id_card : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入证件号码"
                            }
                        },
                        {
                            type: InputType.antd_input,
                            label: "地址",
                            decorator_id: "address",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入地址" }],
                                initialValue: base_data.personnel_info ? base_data.personnel_info.address : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入地址"
                            }
                        }, {
                            type: InputType.antd_input,
                            label: "联系电话",
                            decorator_id: "telephone",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入联系电话" }],
                                initialValue: base_data.personnel_info ? base_data.personnel_info.telephone : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入联系电话"
                            }
                        },
                        {
                            type: InputType.select,
                            label: "服务商",
                            decorator_id: "service_provider_id",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入服务商" }],
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请选择服务商",
                                childrens: org_type_list,
                                onChange: this.service_providerChange,
                                showSearch: true,
                                optionFilterProp: "children",
                                filterOption: (input: any, option: any) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0

                            }
                        },
                        {
                            type: InputType.select,
                            label: "产品类型",
                            decorator_id: "product_type",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请选择购买产品类型" }],
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请选择购买产品类型",
                                childrens: product_type_dom,
                                onChange: this.product_type_change,
                            }
                        }, {
                            type: InputType.select,
                            label: "服务产品",
                            decorator_id: "service_product_id",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请选择服务产品" }],

                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请选择服务产品",
                                childrens: service_list,
                                onChange: this.service_change,
                                showSearch: true,
                                optionFilterProp: "children",
                                filterOption: (input: any, option: any) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        },
                        {
                            type: InputType.antd_input,
                            label: "产品价格",
                            decorator_id: "amout",
                            field_decorator_option: {
                                rules: [{ required: false, message: "" }],
                                initialValue: this.state.total_price,
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "金额",
                                disabled: true,
                            }
                        }, {
                            type: InputType.select,
                            label: "购买账户类型",
                            decorator_id: "buy_type",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请选择购买账户类型" }],
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请选择购买账户类型",
                                childrens: buy_type_dom,
                                onChange: this.account_type_change,
                            }
                        },
                        {
                            type: InputType.antd_input,
                            label: "账户余额",
                            decorator_id: "balance",
                            field_decorator_option: {
                                rules: [{ required: false, message: "" }],
                                initialValue: this.state.balance,
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "账户余额",
                                disabled: true,
                            }
                        },
                        {
                            type: InputType.text_area,
                            label: "备注",
                            decorator_id: "comment",
                            field_decorator_option: {
                                initialValue: '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入备注",
                                row: 3,
                            }
                        },
                    ]
                }
            ],
            other_btn_propps: [
            ],
            submit_btn_propps: {
                text: "确定",
                cb: this.handleSubmit
            },
            service_option: service_option,
            id: this.props.id,
        };
        // let succ_func = () => { this.props.history!.push(ROUTE_PATH.organization); }
        let edit_props_list = Object.assign(edit_props, edit_props_info);
        return (
            (
                <MainContent>
                    <FormCreator {...edit_props_list} />
                </MainContent>
            )
        );
    }
}

/**
 * 控件：帮长者购买服务编辑控件
 * @description 帮长者购买服务编辑控件
 * @author
 */
@addon('BuyServiceView', '帮长者购买服务编辑控件', '帮长者购买服务编辑控件')
@reactControl(BuyServiceView, true)
export class BuyServiceViewControl extends ReactViewControl {
    /** 视图权限 */
    public permission?: Permission;

}